/**
 * @description user module
 * @author Zhangbin
 */
import { Commit } from 'vuex'
import { setUserInfo, getUserInfo } from '@/utils/cookies'
import { UserInfoType } from '@/store/types'
import * as types from '@/store/mutation-types'

// state
const { token, id, name, roles } = getUserInfo('userinfo');
const state: UserInfoType = { token, id, name, roles };

// mutations
const mutations = {
  [types.SET_USERINFO](state: UserInfoType, payload: UserInfoType) {
    setUserInfo('userinfo', payload);
    state.token = payload.token;
    state.id = payload.id;
    state.name = payload.name;
    state.roles = payload.roles;
  },
  [types.CLEAR_USERINFO](state: UserInfoType, payload: any) {
    state.token = '';
    state.id = '';
    state.name = '';
    state.roles = [''];
  }
};

// async actions
const actions = {
  [types.SET_USERINFO]: (context: { commit: Commit, state: UserInfoType }, payload: UserInfoType) => {
    context.commit(types.SET_USERINFO, payload)
  },
};

export const userStore = {
  state,
  mutations,
  actions
}